package com.xbn.xbnmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xbn.xbnmall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbn.common.utils.PageUtils;
import com.xbn.common.utils.Query;

import com.xbn.xbnmall.product.dao.CategoryDao;
import com.xbn.xbnmall.product.entity.CategoryEntity;
import com.xbn.xbnmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CategoryBrandRelationServiceImpl categoryBrandRelationService;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //先查出所有的分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //对这些分类数据进行结构化整理
        //首先找到所有的一级分类，所有的一级分类它们的父分类ID都是0
        List<CategoryEntity> level1Menus = categoryEntities.stream().filter((categoryEntity ->
             categoryEntity.getParentCid() == 0
        )).map((menu)->{
            //将菜单添加到集合中之前，先设置它的子菜单
            menu.setChildren(getChildrens(menu,categoryEntities));
            return menu;
        })
                //对菜单进行排序
                .sorted((menu1,menu2)->{
                    //这里要考虑为空的清空
                    return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return level1Menus;
    }

    /*
    * 删除之前要先检查这个分类有没有子分类存在，如果有子分类存在，那么不允许删除
    * */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /*
    * 找到从一级分类到三级分类的完整路径
    * 格式[父/子/孙]  路径 比如[2,26,226]
    * */
    @Override
    public Long[] findCatelogPath(Long categoryId) {
        List<Long> paths=new ArrayList<>();
        List<Long> parentPath = findParentPath(categoryId, paths);
        //逆序一下，父结点应该要在数组的前面。
        Collections.reverse(parentPath);
        return ( paths.toArray(new Long[parentPath.size()]));

    }
    /*
    * 除了更新自己，还要更新其它表的冗余字段
    * */

 /*   @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })*/
 @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        //先更新自己的表
        this.updateById(category);
        //TODO 冗余字段更新，分类Category
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }
    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .eq("cat_level", 1));
        return categoryEntities;
    }

    //Redisson实现的分布式锁
    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisson() throws InterruptedException {
            //分布式占锁
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        System.out.println("获取锁成功");
            Map<Long, List<Catelog2Vo>> dataFromDb=new HashMap<>();
            try {
                dataFromDb = getDataFromDb();
            }finally {
                lock.unlock();
            }


            return dataFromDb;


    }




    //redis实现的分布式锁
    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() throws InterruptedException {
        String uuid = UUID.randomUUID().toString();
        //uuid为锁的唯一标识
        Boolean catalogSearchLock = redisTemplate.opsForValue().setIfAbsent("catalogSearchLock",uuid,300,TimeUnit.SECONDS);
        //获取锁成功
        if(catalogSearchLock)
        {
            System.out.println("获取锁成功");
            Map<Long, List<Catelog2Vo>> dataFromDb=new HashMap<>();
            try {
                dataFromDb = getDataFromDb();
            }finally {
                //解锁必须使用脚本来保证原子性,return 1删除成功,return 0删除失败
                //keys[1]就是我们传入的catalogSearchLock,arvg[1]就是我们传入的uuid
                String script="if redis.call('get',KEYS[1]) == ARGV[1] then   return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class
                ),Arrays.asList("catalogSearchLock"),uuid);
                System.out.println("释放锁成功");
            }


            return dataFromDb;
        }
            else {
        //获取锁失败重试,自旋
            System.out.println("获取锁失败");
            Thread.sleep(100);
            return getCatalogJsonFromDbWithRedisLock();
        }

    }

    private Map<Long, List<Catelog2Vo>> getDataFromDb() {
        if (redisTemplate.opsForValue().get("catalogJson") != null) {

            String jsonString = redisTemplate.opsForValue().get("catalogJson");
            return JSON.parseObject(jsonString, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
            });
        } else {
             System.out.println("查询了数据库");
            List<CategoryEntity> selectList = baseMapper.selectList(null);
            Map<Long, List<Catelog2Vo>> catalogJson = new HashMap<>();

            //查出所有的一级分类
            List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
            //2、封装数据
            catalogJson = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(),
                    v -> {
                        //查找二级分类
                        List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                        List<Catelog2Vo> catelog2Vos = null;


                        if (categoryEntities != null) {
                            catelog2Vos = categoryEntities.stream().map(cateLog2 -> {
                                Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(),
                                        null, cateLog2.getCatId().toString(), cateLog2.getName());
                                //三级菜单查找
                                List<CategoryEntity> level3Catelog = getParent_cid(selectList, cateLog2.getCatId());
                                if (level3Catelog != null) {
                                    List<Catelog2Vo.Catelog3Vo> catelog3VoList = level3Catelog.stream().map(category3 -> {
                                        Catelog2Vo.Catelog3Vo catelog3Vo =
                                                new Catelog2Vo.Catelog3Vo(cateLog2.getCatId().toString(), category3.getCatId().toString(), category3.getName());
                                        return catelog3Vo;
                                    }).collect(Collectors.toList());
                                    catelog2Vo.setCatalog3List(catelog3VoList);
                                    catelog2Vo.setCatalog3List(catelog3VoList);
                                }
                                return catelog2Vo;
                            }).collect(Collectors.toList());
                        }

                        return catelog2Vos;
                    }));
            String s = JSON.toJSONString(catalogJson);
            redisTemplate.opsForValue().set("catalogJson", s,
                    1, TimeUnit.DAYS);
            return catalogJson;
        }
    }

    //本地锁
    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDb() {
        synchronized (this) {
            return getDataFromDb();
        }
    }



    //使用缓存注解
/*
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<Long, List<Catelog2Vo>> getCatalogJson() throws InterruptedException {
        System.out.println("查询了数据库");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        Map<Long, List<Catelog2Vo>> catalogJson = new HashMap<>();

        //查出所有的一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //2、封装数据
        catalogJson = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(),
                v -> {
                    //查找二级分类
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                    List<Catelog2Vo> catelog2Vos = null;


                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(cateLog2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(),
                                    null, cateLog2.getCatId().toString(), cateLog2.getName());
                            //三级菜单查找
                            List<CategoryEntity> level3Catelog = getParent_cid(selectList, cateLog2.getCatId());
                            if (level3Catelog != null) {
                                List<Catelog2Vo.Catelog3Vo> catelog3VoList = level3Catelog.stream().map(category3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo =
                                            new Catelog2Vo.Catelog3Vo(cateLog2.getCatId().toString(), category3.getCatId().toString(), category3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(catelog3VoList);
                                catelog2Vo.setCatalog3List(catelog3VoList);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }

                    return catelog2Vos;
                }));
        return catalogJson;
    }
*/

     @Override
    public Map<Long, List<Catelog2Vo>> getCatalogJson() throws InterruptedException {

            Map<Long, List<Catelog2Vo>> catalogJson = new HashMap<>();
            if (redisTemplate.opsForValue().get("catalogJson") == null) {
                System.out.println("缓存未命中");
               //catalogJson = getCatalogJsonFromDb();
              //  catalogJson= getCatalogJsonFromDbWithRedisLock();
            catalogJson = getCatalogJsonFromDbWithRedisson();
                String s = JSON.toJSONString(catalogJson);
                redisTemplate.opsForValue().set("catalogJson", s,
                        1, TimeUnit.DAYS);
            } else {
                String jsonString = redisTemplate.opsForValue().get("catalogJson");
                catalogJson = JSON.parseObject(jsonString, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
                });
            }
            return catalogJson;

    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> list,Long parent_cid) {
        /*return baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .eq("parent_cid", v.getCatId()));*/
        List<CategoryEntity> collect = list.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());
        return collect;
    }

    /*
    * 递归查找三级分类的父节点
    * */
    private List<Long> findParentPath(Long categoryId,  List<Long> paths){
        //手机当前结点id
        paths.add(categoryId);
        CategoryEntity entity=this.getById(categoryId);
        //如果这个分类有父分类
        if(entity.getParentCid()!=0)
        {
            findParentPath(entity.getParentCid(),paths);
        }
        return paths;
    }


    /*
    * 获取当前菜单的子菜单，递归
    * param1 root :需要获取子菜单的菜单
    * param2 all 从这个集合中查找参数1的子菜单
    * */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //如果all中菜单的父id等于当前菜单的id，说明这个菜单就是root的子菜单
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //子菜单也可能存在子菜单，这里给子菜单尝试寻找它的子菜单，递归
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //这里要考虑为空的清空
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }
}